package com.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/6/13 21:49
 * @since JDK 1.8
 */
@RestController
@RequestMapping("consumer")
public class ConsumerController {


    //用服务名代替
    private final String PROVIDER_Name = "http://feign-provider";


    @Autowired
    private RestTemplate restTemplate;

    /**
     * 使用配置好的 restTemplate 进行负载均衡
     * @return
     */
    @RequestMapping("/get")
    public String getRibboController() {
        String url = PROVIDER_Name + "/test/provider";
        String result = restTemplate.getForObject(url, String.class);
        return result;
    }

    @Autowired
    private DiscoveryClient discoveryClient ;

    /**
     * 使用服务的发现能力
     */
    @GetMapping("/get2")
    public String rpcV2(){
        // 利用服务发现，我们可以动态的发现服务
        List<ServiceInstance> instances = discoveryClient.getInstances("feign-provider");
        // 到底调用哪一个，由负载均衡决定
        String url = loadBalance(instances) ;
        String result = restTemplate.getForObject(url+"/test/provider", String.class);
        return ResponseEntity.ok(result).toString() ;
    }


    /**
     * 自己写的负载均衡
     * @param instances
     * @return
     */
    private String loadBalance(List<ServiceInstance> instances) {
        if(instances==null || instances.isEmpty()){
            throw  new RuntimeException("没有服务的提供者");
        }
        ServiceInstance serviceInstance = instances.get(0);
        return "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort() ;
    }




}
